#include "board.h"

void *board_TCP(void *arg)
{
    // 创建TCP
    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    // 准备好开发板的地址
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    bzero(&addr, len);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(50001);

    // 绑定sockfd和地址
    if(bind(sockfd, (struct sockaddr *)&addr, len) == -1)
    {
        perror("绑定地址失败");
        exit(0);
    }

    // 设定监听状态
    listen(sockfd, 1);

    while(1)
    {
        // 等待客户端的请求
        struct sockaddr_in peeraddr;
        len = sizeof(peeraddr);
        bzero(&peeraddr, len);
        connfd = accept(sockfd, (struct sockaddr *)&peeraddr, &len);
        if(connfd == -1)
        {
            perror("connfd 失败");
            exit(0);
        }
        else
        {
            printf("accept 成功\n");      

            while(1)
            {
                // bzero(buf, 50);
                int n;
                if((n = read(connfd, buf, 50)) == -1)
                {
                    perror("read failed");
                    break;
                }
                else if(n == 0)
                {
                    printf("连接断开\n");
                    break;                
                }
                else
                {
                    printf("%s\n", buf);  
                    char *delim = "-";
                    sscanf(buf, "%d-", &num_tcp);
                    name_tcp = strstr(buf, delim) + 1;
                    printf("序号:%d\t姓名:%s\n",num_tcp, name_tcp);

                }
            }        
        }        
    }
}

void handle(int i, char *h)
{
    if(i == 1)
    {
        printf("%d\t%s\n", i, h);
    }
}

list init_list(void)//初始链表头节点
{
    list new = calloc(1,sizeof(list1));
    if(new != NULL)
    {
        new->next = new;
        new->prve = new;
    }
    new->size = 0;
    return new;
}

list new_node(int num_tcp, char *name_tcp)//创建新节点
{
    list new = calloc(1, sizeof(list1));
    if(new != NULL)
    {
        new->next = new;
        new->prve = new;
    }
    strcpy(new->name, name_tcp);
    return new;
}

bool is_full(list head)
{
    return head->size == 7;
}

bool add_node(list head, list new)//添加节点
{
    if(is_full(head))
    {
        return false;
    }

    new->prve = head;
    new->next = head->next;

    head->next = new;
    new->next->prve = new;

    head->size++;

    return true;
}


bool is_empty(list head)//判断节点个数
{
    return head->size == 0;
}

bool del_node(list head)//删除最后节点
{
    if(is_empty(head))
        return false;

    list p = head->prve;
    p->prve->next = head;
    head->prve = p->prve;
    head->size--;

    free(p);

    return true;
}

void show(list head)//遍历输出信息
{
    for(list p = head->next; p != head; p = p->next)
    {
        printf("姓名%s\n", p->name);
    }
}